<template>
  <view class="table-list">
    <view class="list-box">
      <view class="title">球桌预约详情</view>
      <view class="current-table">当前预约球桌：{{ currentTable }}</view>

      <!-- 日期选择 -->
      <scroll-view class="date-selector" scroll-x>
        <view class="date-container">
          <view class="date-item" v-for="(date, index) in availableDates" :key="index"
            :class="{ active: selectedDateIndex === index }" @click="selectDate(index)">
            <text class="week">{{ date.week }}</text>
            <text class="date">{{ date.date }}</text>
          </view>
        </view>
      </scroll-view>

      <!-- 时间选择 -->
      <view class="time-selector">
        <view class="section-title">选择预约时间</view>
        <view class="time-grid">
          <view class="time-item" v-for="(time, index) in timeSlots" :key="index"
            :class="{ active: selectedTimeSlots.includes(index), disabled: !time.available }"
            @click="selectTime(index, time.available)">
            <text class="time-text">{{ formatTimeDisplay(time.startTime) }}-{{ formatTimeDisplay(time.endTime) }}</text>
            <text class="price">¥{{ currentPrice }}/小时</text>
          </view>
        </view>
      </view>

      <!-- 预约按钮 -->
      <view class="reserve-button-container">
        <button class="reserve-button" @click="showReservationModal" :disabled="selectedTimeSlots.length === 0">
          立即预约
        </button>
      </view>

      <!-- 预约确认弹窗 -->
      <view class="modal" v-if="showModal" @touchmove.stop.prevent>
        <view class="modal-content">
          <view class="modal-header">
            <text class="modal-title">预约确认</text>
            <view class="close-btn" @click="closeModal">×</view>
          </view>
          <view class="modal-body">
            <view class="reservation-info">
              <view class="info-item">
                <text class="label">球桌：</text>
                <text class="value">{{ currentTable }}</text>
              </view>
              <view class="info-item">
                <text class="label">日期：</text>
                <text class="value">{{ selectedDateInfo.date }} {{ selectedDateInfo.week }}</text>
              </view>
              <view class="info-item">
                <text class="label">预约时间：</text>
                <view class="value">
                  <view class="time-slot-item" v-for="(time, index) in selectedTimeSlotsInfo" :key="index">
                    {{ formatTimeDisplay(time.startTime) }}-{{ formatTimeDisplay(time.endTime) }}
                  </view>
                </view>
              </view>
              <view class="info-item">
                <text class="label">时长：</text>
                <text class="value">{{ selectedTimeSlots.length }}小时</text>
              </view>
              <view class="info-item">
                <text class="label">费用：</text>
                <text class="value price">¥{{ totalPrice }}</text>
              </view>
            </view>
          </view>
          <view class="modal-footer">
            <button class="pay-button" @click="pay">去支付</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getProductDetails, getProductApptTimeSlotByDate } from '@/services/product.js';
import { createOrder } from '@/services/order.js';

const currentTable = ref('');
const currentTableData = ref(null);
const selectedDateIndex = ref(0);
const selectedTimeSlots = ref([]);
const showModal = ref(false);
const userInfo = ref({});

// 可预约的时间范围配置
const timeSlotsConfig = ref([]);

// 生成可预约的日期（今天开始往后一周）
const availableDates = computed(() => {
  const dates = [];
  const weekMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  for (let i = 0; i < 7; i++) {
    const date = new Date();
    date.setDate(date.getDate() + i);
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const week = weekMap[date.getDay()];
    dates.push({
      week: week,
      date: `${month}-${day}`
    });
  }
  return dates;
});

// 生成时间选项卡
const timeSlots = computed(() => {
  return timeSlotsConfig.value;
});

// 当前选中的日期信息
const selectedDateInfo = computed(() => {
  if (selectedDateIndex.value !== null && availableDates.value.length > 0) {
    const today = new Date();
    const selectedDate = new Date();
    selectedDate.setDate(today.getDate() + selectedDateIndex.value);
    const year = selectedDate.getFullYear();
    const month = (selectedDate.getMonth() + 1).toString().padStart(2, '0');
    const day = selectedDate.getDate().toString().padStart(2, '0');
    return {
      ...availableDates.value[selectedDateIndex.value],
      fullDate: `${year}-${month}-${day}`
    };
  }
  return {};
});

// 当前选中的时间信息数组
const selectedTimeSlotsInfo = computed(() => {
  return selectedTimeSlots.value.map(index => timeSlots.value[index]);
});

// 当前价格
const currentPrice = computed(() => {
  return currentTableData.value ? currentTableData.value.price : 0;
});

// 总价格
const totalPrice = computed(() => {
  return currentPrice.value * selectedTimeSlots.value.length;
});

// 页面加载时获取参数
onLoad(async (options) => {
  try {
    // 获取用户配置信息
    const userConfig = uni.getStorageSync('userConfig');
    if (userConfig) {
      userInfo.value = userConfig;
    }
  } catch (error) {
    console.error('获取用户配置失败：', error);
  }

  if (options && options.tableId) {
    const tableId = parseInt(options.tableId);
    try {
      const res = await getProductDetails(tableId);
      if (res.code === 200) {
        currentTableData.value = res.data;
        currentTable.value = res.data.name;
        // 获取默认日期的可预约时间段
        await fetchTimeSlots(tableId, selectedDateInfo.value.fullDate);
      }
    } catch (error) {
      console.error('获取商品详情失败：', error);
    }
  }
});

// 时间格式化函数
const formatTimeDisplay = (timeString) => {
  if (!timeString) return '';
  const parts = timeString.split(':');
  if (parts.length >= 2) {
    return `${parts[0]}:${parts[1]}`;
  }
  return timeString;
};

// 获取可预约时间
const fetchTimeSlots = async (productId, date) => {
  try {
    const res = await getProductApptTimeSlotByDate(productId, date);
    if (res.code === 200) {
      // 更新时间槽配置
      timeSlotsConfig.value = res.data.map(item => ({
        startTime: item.dateTimeRange.startTime,
        endTime: item.dateTimeRange.endTime,
        available: item.state === 0 // state为0表示可预约
      }));
    }
  } catch (error) {
    console.error('获取可预约时间失败：', error);
  }
};

// 选择日期
const selectDate = async (index) => {
  selectedDateIndex.value = index;
  // 重置时间选择
  selectedTimeSlots.value = [];
  // 获取选中日期的可预约时间槽
  if (currentTableData.value) {
    await fetchTimeSlots(currentTableData.value.id, selectedDateInfo.value.fullDate);
  }
};

// 选择时间
const selectTime = (index, isAvailable) => {
  // 如果时间不可选，则不执行任何操作
  if (!isAvailable) {
    return;
  }
  // 切换选择状态
  const selectedIndex = selectedTimeSlots.value.indexOf(index);
  if (selectedIndex > -1) {
    // 如果已选中，则取消选择
    selectedTimeSlots.value.splice(selectedIndex, 1);
  } else {
    // 如果未选中，则添加到选择列表
    selectedTimeSlots.value.push(index);
  }
};

// 显示预约确认弹窗
const showReservationModal = () => {
  if (selectedTimeSlots.value.length > 0) {
    showModal.value = true;
    // 禁止背景滚动
    document.body.style.overflow = 'hidden';
  }
};

// 关闭弹窗
const closeModal = async () => {
  showModal.value = false;
  // 恢复背景滚动
  document.body.style.overflow = '';
  // 关闭弹窗时刷新当前日期的时间段数据
  if (currentTableData.value) {
    await fetchTimeSlots(currentTableData.value.id, selectedDateInfo.value.fullDate);
  }
};

// 支付
const pay = async () => {
  // 构造订单数据
  const orderData = {
    productId: currentTableData.value.id,
    timeRangeDTOList: selectedTimeSlotsInfo.value.map(time => {
      const currentDate = selectedDateInfo.value.fullDate;
      return {
        startTime: `${currentDate} ${time.startTime}`,
        endTime: `${currentDate} ${time.endTime}`
      };
    })
  };
  try {
    const res = await createOrder(orderData);
    if (res.code === 200) {
      // 创建订单成功，跳转到订单详情界面
      uni.navigateTo({
        url: `/pages/list/payDetail?orderNo=${res.data}`
      });
      closeModal();
    } else {
      // 创建订单失败，提示错误信息
      uni.showToast({
        title: res.message || '创建订单失败',
        icon: 'none'
      });
    }
  } catch (error) {
    // 网络或其他异常，提示用户
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
    console.error('创建订单失败：', error);
  }
};
</script>

<style lang="scss">
.table-list {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(110.13deg, rgba(172, 206, 242, 1) 0%, rgba(255, 255, 255, 1) 100%);

  .list-box {
    padding: 15px;

    .title {
      font-size: 20px;
      text-align: center;
      margin: 10px 0;
      font-weight: 700;
      color: rgba(81, 89, 245, 1);
    }

    .current-table {
      font-size: 16px;
      text-align: center;
      margin-bottom: 20px;
      color: #333;
    }

    // 日期选择器
    .date-selector {
      white-space: nowrap;
      margin-bottom: 30px;
      padding: 10px 10px 10px 8px;
      background-color: #fff;
      border-radius: 10px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

      .date-container {
        display: flex;
        flex-direction: row;
        padding: 0 10px;

        .date-item {
          flex: 1;
          min-width: 60px;
          padding: 10px 5px;
          margin-right: 10px;
          text-align: center;
          border-radius: 8px;
          background-color: #fff;
          border: 1px solid #e0e0e0;
          transition: all 0.3s ease;

          .week {
            display: block;
            font-size: 14px;
            color: #333;
            margin-bottom: 5px;
          }

          .date {
            display: block;
            font-size: 12px;
            color: #333;
          }

          &.active {
            background-color: #165dff;
            border-color: #165dff;

            .week,
            .date {
              color: #fff;
            }
          }
        }
      }
    }

    // 时间选择器
    .time-selector {
      margin-bottom: 30px;

      .section-title {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 15px;
        color: #333;
      }

      .time-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 10px;

        .time-item {
          background-color: #f5f5f5;
          border-radius: 8px;
          padding: 15px 5px;
          text-align: center;
          cursor: pointer;

          &.active {
            background-color: #165dff;
            color: #fff;
          }

          &.disabled {
            background-color: #f0f0f0;
            color: #999;
            cursor: not-allowed;
            opacity: 0.6;

            .price {
              color: #999;
            }
          }

          .time-text {
            display: block;
            font-size: 14px;
            margin-bottom: 5px;
          }

          .price {
            display: block;
            font-size: 12px;
          }
        }
      }
    }

    // 预约按钮
    .reserve-button-container {
      padding: 20px 0;

      .reserve-button {
        width: 100%;
        background-color: #165dff;
        color: #fff;
        border: none;
        padding: 15px;
        font-size: 16px;
        border-radius: 8px;

        &[disabled] {
          background-color: #ccc;
        }
      }
    }
  }

  // 弹窗样式
  .modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;

    .modal-content {
      background-color: #fff;
      border-radius: 10px;
      width: 75%;
      max-width: 400px;
      padding: 20px;

      .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;

        .modal-title {
          font-size: 18px;
          font-weight: bold;
        }

        .close-btn {
          font-size: 24px;
          cursor: pointer;
        }
      }

      .modal-body {
        .reservation-info {
          .info-item {
            display: flex;
            margin-bottom: 15px;

            .label {
              flex: 1;
              color: #666;
            }

            .value {
              flex: 2;
              color: #333;

              &.price {
                color: #ff6600;
                font-weight: bold;
              }

              .time-slot-item {
                margin-bottom: 5px;
              }
            }
          }
        }
      }

      .modal-footer {
        margin-top: 20px;

        .pay-button {
          width: 100%;
          background-color: #165dff;
          color: #fff;
          border: none;
          padding: 8px 15px;
          font-size: 16px;
          border-radius: 8px;
        }
      }
    }
  }
}
</style>